package com.jsmy.marketing;

import java.io.IOException;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author leitao
 * @fileName pkg.shi.com.model.bean
 * @date 2016/4/20
 * @update by     on
 */
public class MModelImpl<T> {

    public void loadData(Call call, final String position, final OnLoadDataListener listener){
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    listener.onSuccess(response.body().string(),position);
//                    Log.d("okhttp3.0",response.body().string().toString());
                } catch (IOException e) {
                    listener.onFailure(e.getMessage());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                listener.onFailure("请保持网络通畅"+t.getMessage());
            }
        });
    }

    public void loadData(Observable<T> observable, final String position, final OnLoadDataListener listener){
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<T>() {

            @Override
            public void accept(@NonNull T t) throws Exception {
                listener.onSuccess(t, position);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(@NonNull Throwable throwable) throws Exception {
                listener.onFailure(throwable.getMessage());
            }
        });
    }
    public interface OnLoadDataListener{
        void onSuccess(Object response, String position);
        void onFailure(String msg);
    }

}
